import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;
/*
题目描述
从上到下按层打印二叉树，同一层结点从左至右输出。每一层输出一行。

思路：
（1）每一层最后设置null


*/

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}

public class Solution {
    ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> result  = new ArrayList<>();
        ArrayList<Integer> lineList ;
        Queue<TreeNode> queue = new ArrayDeque<>();
        TreeNode levelNode = new TreeNode(-1);
        TreeNode tempNode;
        if(pRoot==null)
            return result;
        else{
            queue.add(pRoot);
            queue.add(levelNode);
            lineList = new ArrayList<>();
            while(!queue.isEmpty()){
                tempNode = queue.poll();
                if(tempNode==levelNode){
                    result.add(lineList);
                    lineList=new ArrayList<>();
                    if(!queue.isEmpty())
                        queue.add(levelNode);
                }else{
                    lineList.add(tempNode.val);
                    if(tempNode.left!=null)
                        queue.add(tempNode.left);
                    if(tempNode.right!=null)
                        queue.add(tempNode.right);
                }
            }
        }
        return result;
    }
    public static void main(String args[]){
        Solution s = new Solution();
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);

        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        s.Print(node1);
    }

}